#include "TcpServer.hpp"
#include <string>
#include <memory>

void Usage(std::string proc)
{
    std::cout << "\n\tUsage:\n\t\t" << proc << "\tport\n"
              << std::endl;
}

void Calculate(tcpsvr::Connection *conn)
{
    std::string package; // 报文
    while (ParseOneMsg(&package, conn->inbuffer_))
    {
        // logMessage(DEBUG, "ParseOneMsg success, package: %s", package);
        std::string reqTxt;
        if(!deLength(package, &reqTxt)) return;
        Request req;
        if(!req.deserialization(reqTxt)) return;
        Response resp;
        cal(req, &resp);
        
        std::string respTxt;
        if(!resp.serialization(&respTxt)) return;
        std::string send_str = enLength(respTxt);
        conn->outbuffer_ += send_str;
        std::cout << send_str << std::endl;
        conn->sender_(conn);
        
    }
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
    }
    uint16_t port = atoi(argv[1]);

    std::unique_ptr<tcpsvr::TcpServer> tse(new tcpsvr::TcpServer(Calculate, port));
    tse->initServer();
    tse->Dispatch();

    return 0;
}